/*
 * @Author: xiaoyan
 * @Date: 2021-11-19 17:34:07
 * @LastEditors: xiaoyan
 * @LastEditTime: 2021-12-06 14:30:19
 * @Description: 
 * @FilePath: \user_auth_front\src\components\header\index.tsx
 */
import { Breadcrumb,Avatar,Dropdown,Menu,Tooltip, Button } from 'antd';
import { HomeOutlined,UserOutlined,MenuFoldOutlined,MenuUnfoldOutlined  } from '@ant-design/icons';
import "./index.scss"
import React from 'react';
import { useDispatch, useMappedState } from 'redux-react-hook';
import { setCollapsed } from "@/store/modules/app"
import { removeToken } from "@/store/modules/user"
import { useNavigate,useLocation,Link } from "react-router-dom";
import { removeToken as delToken} from '@/utils/storage'
import {menus} from "@/constant"
export default ()=>{
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const location = useLocation();
    const collapsed = useMappedState(state=>state.app.collapsed);
    const changeCollapsed = ()=>{
        const action = setCollapsed(!collapsed);
        dispatch(action);
    };
    const logout = ()=>{
        delToken();
        const action = removeToken();
        dispatch(action);
        navigate('/login');
    };
    const menu = (
        <Menu>
            <Menu.Item key="logout" onClick={logout}>退出</Menu.Item>
        </Menu>
    );
    const userName = "admin";

    const breadcrumb = ()=>{
        interface MenuObj {
            [key:string]:string
        }
        const breadcrumbNameMap:MenuObj = {};
        menus.forEach(item=>{
            breadcrumbNameMap[item.path] = item.title;
        });
        const pathSnippets = location.pathname.split('/').filter(i => i);
        const extraBreadcrumbItems = pathSnippets.map((_, index) => {
            const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
            return (
            <Breadcrumb.Item key={url}>
                <Link to={url}>{breadcrumbNameMap[url]}</Link>
            </Breadcrumb.Item>
            );
        });
        return [
            <Breadcrumb.Item key="/home">
              <Link to="/home"><HomeOutlined /></Link>
            </Breadcrumb.Item>,
          ].concat(extraBreadcrumbItems); 
    }
    const breadcrumbItems = breadcrumb();
    return(
        <div className="header">
            <div className="header-l">
                <Button type="text" onClick={changeCollapsed} >
                    {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined)}
                </Button>
                <Breadcrumb>{breadcrumbItems}</Breadcrumb>
            </div>
            <Dropdown overlay={menu}>
                <Tooltip placement="left" title={userName}>
                    <Avatar size={30} icon={<UserOutlined/>} />
                </Tooltip>
            </Dropdown>
        </div>
    )
}